package com.concise.appapi.service;

import com.concise.appapi.service.model.TheArticleListsModel;
import com.initialize.pub.dao.ClassificationDAO;
import com.initialize.pub.generate.pojo.Article;
import com.initialize.pub.generate.pojo.Classification;
import com.initialize.pub.pojo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: concise-blog
 * @description:
 * @author: Mr.Jane
 * @create: 2019-10-16 15:57
 **/
@Service
public class ClassificationService {
    @Autowired
    ClassificationDAO classificationDAO;

    @Autowired
    ArticleService articleService;

    public Result getAllTheCategories() {

        List<Classification> classificationList = classificationDAO.getAllTheCategories();
        List<Map<String, Object>> mapList = classificationToModel(classificationList);
        return Result.success(mapList);
    }

    private List<Map<String, Object>> classificationToModel(List<Classification> classificationList) {

        List<Map<String, Object>> mapList = new ArrayList<>();
        for (Classification classification : classificationList) {
            Integer ccid = classification.getCcid();
            //获取一级分类
            if (ccid == 0) {
                Integer cid = classification.getCid();
                Map<String, Object> stringObjectMap = new LinkedHashMap<>();
                stringObjectMap.put("level_1", classification.getName());
                stringObjectMap.put("id", classification.getCid());
                //获取二级分类
                List<Map<String, Object>> classificationList1 = new ArrayList<>();
                for (Classification classification1 : classificationList) {
                    boolean b = classification1.getCcid().equals(cid);
                    if (b) {
                        Map<String, Object> stringObjectMap1 = new LinkedHashMap<>();
                        stringObjectMap1.put("level_1", classification1.getName());
                        stringObjectMap1.put("id", classification1.getCid());
                        classificationList1.add(stringObjectMap1);
                    }
                }
                stringObjectMap.put("level_2", classificationList1);
                mapList.add(stringObjectMap);
            }
        }

        return mapList;
    }

    public List<TheArticleListsModel> getsArticlesForEachCategory(int id) {
        List<Article> articleList = classificationDAO.getsArticlesForEachCategory(id);
        List<TheArticleListsModel> theArticleListsModels = articleService.articleToArticleListModel(articleList);

        return theArticleListsModels;
    }

    public int getTheNumberOfCategories() {
        return classificationDAO.selNum();
    }
}
